package com.major.crowd.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.major.crowd.constant.CrowdConstant;
import com.major.crowd.entity.Admin;
import com.major.crowd.entity.AdminExample;
import com.major.crowd.exception.LoginFailedException;
import com.major.crowd.mapper.AdminMapper;
import com.major.crowd.service.api.AdminService;
import com.major.crowd.util.CrowdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /*private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder){
        this.passwordEncoder = passwordEncoder;
    }*/

    //新增
    public void saveAdmin(Admin admin) {
        //密码加密
        String userPswd = admin.getUserPswd();
        // userPswd = CrowdUtil.md5(userPswd);
        userPswd = passwordEncoder.encode(userPswd);
        admin.setUserPswd(userPswd);

        //生成创建时间
        Date date =new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = format.format(date);
        admin.setCreateTime(createTime);

        try {
            adminMapper.insert(admin);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    /**
     * 登录验证
     * @param loginAcct
     * @param userPswd
     * @return
     */
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
        // 根据登陆账号查询admin对象
        // 1.创建adminExample对象
        AdminExample adminExample = new AdminExample();

        AdminExample.Criteria criteria = adminExample.createCriteria();

        criteria.andLoginAcctEqualTo(loginAcct);

        List<Admin> admins = adminMapper.selectByExample(adminExample);

        //判断admin是否为null
        if (admins == null || admins.size() == 0){
            System.out.println("判断admins是否为null");
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);

        }
        if (admins.size() > 1){
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        //为null，抛异常
        Admin admin = admins.get(0);
        if (admin == null){
            System.out.println("判断admin是否为null");
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        //不为空，将数据库密码从admin取出
        String userPswdDB = admin.getUserPswd();

        // 对提交的明文密码进行加密
        String userPswdFrom = CrowdUtil.md5(userPswd);

        // 比较密码
        if (!Objects.equals(userPswdDB,userPswdFrom)){
            //System.out.println("比较密码");
            // 结果不一致，抛异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        //一致，返回admin对象
        return admin;
    }

    //分页
    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
        //开启分页功能
        PageHelper.startPage(pageNum,pageSize);

        //执行查询
        List<Admin> list = adminMapper.selectAdminListByKeyword(keyword);

        //封装到pageInfo对象中
        return new PageInfo<>(list);
    }

    //删除单个
    @Override
    public int deleteById(Integer id) {
        int i = adminMapper.deleteByPrimaryKey(id);
        return i;
    }

    @Override
    public Admin queryById(Integer id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(Admin admin) {
        //有选择地跟新，null不更新
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {
        //删除旧的
        adminMapper.deleteOldRelationship(adminId);
        ////关联新的
        if (roleIdList != null && roleIdList.size() > 0){
            adminMapper.insertNewRelationship(adminId,roleIdList);
        }

    }

    @Override
    public Admin getAdminByLoginAcct(String username) {
        AdminExample example = new AdminExample();

        AdminExample.Criteria criteria = example.createCriteria();

        criteria.andLoginAcctEqualTo(username);

        List<Admin> list = adminMapper.selectByExample(example);

        Admin admin = list.get(0);

        return admin;
    }

}
